//
//  AppHelper.swift
//  TestDemoSwift
//
//  Created by 王锦发 on 2020/3/27.
//  Copyright © 2020 WJF. All rights reserved.
//

import UIKit
import Foundation
import HandyJSON
import IQKeyboardManagerSwift

// MARK: - typealias
typealias BKResultHandler = (_ ok: Bool, _ obj: Any?, _ msg: String?, _ code: NetStatusCode) -> Void
typealias BKPayHandler = (_ pram: String?) -> Void
typealias BKQuickLoginHandler = (_ pram: String) -> Void

let YBApp = UIApplication.shared.delegate as! AppDelegate

// MARK: - AppHelper
class AppHelper: NSObject {
    
    enum Keys {
        static let UserKey = "UserKey"
    }
    
    /// 单例
    static let `default` = AppHelper()
    
    /// 登录的用户信息model
    /// 1. 赋值不为空时保存到UserDefaults, 为空时, 从 UserDefaults 移除
    /// 2. 某个属性修改后, 需要重新赋值, 才能将属性的新值保存到 UserDefaults
    var userModel: YBUserModel? {
        get {
            let def = UserDefaults.standard
            guard let data = def.object(forKey: Keys.UserKey) else { return nil }
            
            var model: YBUserModel?
            do {
                model = try JSONDecoder().decode(YBUserModel.self, from: data as! Data)
            } catch { }
            return model
        }
        set {
            if let model = newValue {
                do {
                    let data = try JSONEncoder().encode(model)
                    self.saveUD(data: data, forKey: Keys.UserKey)
                } catch { }
            } else {
                self.removeUD(forKey: Keys.UserKey)
            }
        }
    }
    
    private override init() { }
    
}

// MARK: - 项目配置
extension AppHelper {
    
    /// 开始进入App
    @objc static func startEnterApp(_ window: UIWindow?) {
        if #available(iOS 13.0, *) {
            window?.overrideUserInterfaceStyle = DarkModeTool.mode.style
        }
        IQKeyboardManager.open()
        
        if logined() {
            self.startApp(window)
        } else {
            self.startLogin(window)
        }
    }
    
    /// 开始登录
    static func startLogin(_ window: UIWindow?) {
        let vc = YBLoginVC()
        var navi = BaseNaviVC(rootViewController: vc)
        BaseNaviVC.setNaviBarAppearence(navi: &navi)
        window?.rootViewController = navi
        window?.makeKeyAndVisible()
    }
    
    /// 退出登录
    static func startLogout() {
        // 清除缓存
        self.clearAllUserCache()
        
        // 退出到登录页面
        guard let window = UIApplication.shared.mainWindow() else { return }
        self.startLogin(window)
        
        // 断开SSE
        YBSSEManager.sharedInstance().func__endWithEventSource()
    }
    
    /// 打开首页
    static func startApp(_ window: UIWindow?) {
        let tabBar = BaseTabBarVC()
        window?.rootViewController = tabBar
        window?.makeKeyAndVisible()
    }
    
    /** 验证是否登录*/
    static func logined() -> Bool {
        return AppHelper.token.isValid
    }
    
    /** 清空用户所有缓存信息*/
    static func clearAllUserCache() {
        AppHelper.kUserModel = nil
        AppHelper.token = ""
    }
    
    /** 应用第一次启动*/
    static func isFirstLaunch() -> Bool {
        let isFirstLaunch = !AppHelper.hasBeenLaunched
        if isFirstLaunch {
            AppHelper.hasBeenLaunched = true
        }
        return isFirstLaunch
    }
    
    /** 当前版本第一次启动*/
    static func isFirstLaunchOfNewVersion() -> Bool {
        // 上次启动的版本号
        let lastLaunchVersion = AppHelper.hasBeenLaunchedOfNewVersion
        // 版本号比较
        let isFirstLaunchOfNewVersion = kAppVersion != lastLaunchVersion
        if isFirstLaunchOfNewVersion {
            AppHelper.hasBeenLaunchedOfNewVersion = kAppVersion
        }
        return isFirstLaunchOfNewVersion
    }
    
    /** 用户模型*/
    static var kUserModel: YBUserModel? {
        get { return AppHelper.default.userModel }
        set { AppHelper.default.userModel = newValue }
    }
    
    /** 用户userId*/
    static var kUserId: String {
        return AppHelper.kUserModel?.id ?? ""
    }
    
    /** 用户昵称*/
    static var kNickName: String {
        return AppHelper.kUserModel?.userName ?? ""
    }
    
    /** 用户头像*/
    static var kAvatar: String? {
        return AppHelper.kUserModel?.avatar
    }
    
}

// MARK: - UserDefaults配置
extension AppHelper {
    
    /// 用户 Keys
    enum UserKeys: String {
        case token
        case hasBeenLaunched
        case hasBeenLaunchedOfNewVersion
    }
    
    /// 设置 Keys
    enum SettingKeys: String {
        case appTheme
    }
    
    @UD(key: UserKeys.token.rawValue, defaultValue: "") static var token: String
    @UD(key: UserKeys.hasBeenLaunched.rawValue, defaultValue: false) static var hasBeenLaunched: Bool
    @UD(key: UserKeys.hasBeenLaunchedOfNewVersion.rawValue, defaultValue: "") static var hasBeenLaunchedOfNewVersion: String
    
}

// MARK: - Private
extension AppHelper {
    
    private func saveUD(data: Data, forKey key: String) {
        let def = UserDefaults.standard
        def.set(data, forKey: key)
        def.synchronize()
    }
    
    private func removeUD(forKey key: String) {
        let def = UserDefaults.standard
        def.removeObject(forKey: key)
        def.synchronize()
    }
    
}
